from peewee import SqliteDatabase, DateTimeField, CharField, FloatField, Model

db = SqliteDatabase('./demo.db')


class DataTable(Model):
    '''
    示例数据表
    '''

    # 示例字段1
    field1 = CharField()

    # 示例字段2
    field2 = FloatField()

    class Meta:

        database = db

        table_name = 'data_table'

        primary_key = False


class UpdateRecord(Model):
    '''
    更新记录表
    '''

    # 更新时间字段
    update_datetime = DateTimeField()


    class Meta:

        database = db

        table_name = 'update_record'

        primary_key = False


db.create_tables([DataTable, UpdateRecord])


if __name__ == '__main__':

    import time
    import random
    from datetime import datetime

    # 数据更新示例

    while True:

        # 随机间隔更新一次数据
        time.sleep(random.uniform(5, 10))

        # 模拟数据插入
        DataTable.insert_many([
            {
                'field1': random.sample(list('abcd'), 1)[0],
                'field2': round(random.uniform(0, 100), 3)
            }
            for i in range(10)
        ]).execute()

        # 模拟更新日志表插入
        UpdateRecord.insert_many([
            {
                'update_datetime': datetime.now()
            }
        ]).execute()
        
        print('第{}次更新数据完成'.format(len(UpdateRecord.select().dicts())))

